<script setup>
import * as echarts from "echarts";
import { assign } from "lodash-es";
import { ref, watchEffect } from "vue";

const props = defineProps({
  color: {
    type: Array,
    default: [],
  },
  data: {
    type: Array,
    default: [],
  },
  legend: {
    type: Object,
    default: {},
  },
  title: {
    type: Array | Object,
    default: [],
  },
  radius: {
    type: Array | String,
    default: ["60%", "70%"],
  },
  center: {
    type: Array,
    default: ["50%", "60%"],
  },
});

const chartRef = ref(null);

watchEffect(() => {
  if (!chartRef.value) return;
  const chart = echarts.init(chartRef.value);
  const option = {
    legend: assign(
      {
        bottom: 20,
        left: "38%",
        orient: "vertical",
        itemWidth: 10,
        itemHeight: 10,
        itemGap: 8,
        textStyle: {
          fontSize: 12,
          fontWeight: "bold",
          color: "#FFFFFF",
          rich: {
            name: {
              color: "rgba(201,233,248,0.8)",
              fontSize: 10,
            },
          },
        },
        formatter: (e) => {
          let val = 0;
          props.data.forEach((el) => {
            if (e == el.name) val = el.value;
          });
          return `{name|${e}} ${val}%`;
        },
      },
      props.legend
    ),
    title: props.title,
    color: props.color,
    series: [
      {
        type: "pie",
        radius: props.radius,
        center: props.center,
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: "center",
        },
        labelLine: {
          show: false,
        },
        data: props.data,
      },
    ],
  };
  chart.setOption(option);
});
</script>

<template>
  <div ref="chartRef" style="width: 100%; height: 100%"></div>
</template>
